<template>
  <AxiomDialog
    :model-value="visible"
    :title="`为【${userData?.username}】分配角色`"
    width="500px"
    @close="handleClose"
    @cancel="handleClose"
    @confirm="handleConfirm"
    :loading="listLoading && !isListReady"
    :confirm-loading="confirmButtonLoading"
  >
    <AxiomTree
      ref="treeRef"
      :data="roleTree"
      :loading="listLoading"
      show-checkbox
      node-key="id"
      :props="{ label: 'role_name', children: 'children' }"
      :default-expand-all="true"
    />
  </AxiomDialog>
</template>

<script setup>
import { ref, watch, nextTick, inject } from 'vue';
import { AxiomDialog, AxiomTree } from 'axiom-view';
import { getRoleTree } from '@/api/system/role';
import { getUserDetails, assignRolesToUser } from '@/api/system/user';

const props = defineProps({
  visible: Boolean,
  userData: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(['close', 'success']);
const { notification } = inject('axiom-utils');
const treeRef = ref(null);

const confirmButtonLoading = ref(false);
const listLoading = ref(false);
const roleTree = ref([]);
const checkedRoles = ref([]);
const isListReady = ref(false);

watch(() => props.visible, async (val) => {
  if (val && props.userData) {
    isListReady.value = false;
    await fetchData();
  }
});

const fetchData = async () => {
  listLoading.value = true;
  roleTree.value = [];
  checkedRoles.value = [];
  try {
    const rolesRes = await getRoleTree();
    roleTree.value = (rolesRes.success && rolesRes.data) ? rolesRes.data : [];

    await nextTick();

    const userRes = await getUserDetails(props.userData.id);
    if (userRes.success && userRes.data) {
      checkedRoles.value = userRes.data.roles.map(role => role.id);
      // 使用 setCheckedKeys 来确保回显
      if (treeRef.value) {
        treeRef.value.setCheckedKeys(checkedRoles.value);
      }
    } else {
      checkedRoles.value = [];
    }

    isListReady.value = true;
  } catch (error) {
    console.error('获取角色树或用户信息失败:', error);
  } finally {
    listLoading.value = false;
  }
};

const handleClose = () => {
  roleTree.value = [];
  checkedRoles.value = [];
  isListReady.value = false;
  // 清空树的勾选状态
  if (treeRef.value) {
    treeRef.value.setCheckedKeys([]);
  }
  emit('close');
};

const handleConfirm = async () => {
  if (!treeRef.value) return;

  confirmButtonLoading.value = true;
  try {
    const selectedKeys = treeRef.value.getCheckedKeys();
    await assignRolesToUser(props.userData.id, selectedKeys);
    notification.success({ title: '成功', message: '角色分配成功' });
    emit('success');
    handleClose();
  } catch (error) {
    console.error('分配角色失败:', error);
  } finally {
    confirmButtonLoading.value = false;
  }
};
</script> 